import store from '../../store'
import router from '../../router'
import { removeToken, getToken,setToken } from '@/utils/auth'
import request from '../../utils/request';

const user = {
  state: {
    name: "",
    username: "",
    roleName: '',
    roleId: '',
    userId: '',
    menuList: [],
    permissionList: [],
    deptId: ''
  },
  mutations: {
    SET_USER: (state, userInfo) => {
      state.name = userInfo.name
      state.username = userInfo.username
      state.roleName = userInfo.roleName
      state.roleId = userInfo.roleId
      state.userId = userInfo.userId
      state.menuList = userInfo.menuList
      state.permissionList = userInfo.permissionList
      state.deptId = userInfo.deptId
    },
    RESET_USER: (state) => {
      state.name = "";
      state.username = "";
      state.roleName = '';
      state.roleId = '';
      state.userId = '';
      state.menuList = [];
      state.permissionList = [];
      state.deptId = '';
    }
  },
  actions: {
    // 登录
    Login({ commit, state }, param) {
      let username = param.username;
      let password = param.password;
      return new Promise((resolve, reject) => {
        request({
          url: "login/auth",
          method: "post",
          params: {
            username,password
          }
        }).then(data => {
          if (data.code === 200) {
            //cookie中保存前端登录状态
            console.log("设置登陆状态，存储token" + data.data);
            setToken(data.data);
          }
          resolve(data);
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        request({
          url: '/login/userInfo',
          method: 'get',
        }).then(data => {
          console.log(data);
          //储存用户信息
          commit('SET_USER', data.data);
          //cookie保存登录状态,仅靠vuex保存的话,页面刷新就会丢失登录状态
          
          // if(data.code == 200){
            
          //   setToken(data.data);
          // }
          
          //生成路由
          let userPermission = data.userPermission;
          store.dispatch('GenerateRoutes', userPermission).then(() => {
            //生成该用户的新路由json操作完毕之后,调用vue-router的动态新增路由方法,将新路由添加
            router.addRoutes(store.getters.addRouters)
          })
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve) => {
        request({
          url: "login/logout",
          method: "post"
        }).then(data => {
          commit('RESET_USER')
          removeToken()
          resolve(data);
        }).catch(() => {
          commit('RESET_USER')
          removeToken()
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('RESET_USER')
        removeToken()
        resolve()
      })
    }
  }

}
export default user